<?php

function requirements() {
    global $state;
    global $warning, $fail, $title, $languages, $perms;

    $languages = findLanguages(realpath('./languages'));

    $extensions = get_loaded_extensions();

    $perms['web'] = is_writable(WEBROOT);
    $perms['system'] = is_dir(APPROOT);
    $perms['data'] = is_writable(DATAROOT);
    $perms['backups'] = is_writable(DATAROOT . '/backups');
    $perms['cache'] = is_writable(DATAROOT . '/cache');
    $perms['languages'] = is_writable(DATAROOT . '/languages');
    $perms['logs'] = is_writable(DATAROOT . '/logs');
    $perms['pages'] = is_writable(DATAROOT . '/pages');
    $perms['settings'] = is_writable(DATAROOT . '/settings');
    $perms['thirdparty'] = is_writable(DATAROOT . '/thirdparty');
    $perms['uploads'] = is_writable(DATAROOT . '/uploads');

    $perms['plugins'] = is_writable(APPROOT . '/plugins');
    $perms['themes'] = is_writable(APPROOT . '/themes');

    $simplexml = in_array('SimpleXML', $extensions);
    $zip = in_array('zip', $extensions);
    $imagick = in_array('imagick', $extensions);
    $gd = in_array('gd', $extensions);

    if (!defined('PHP_VERSION_ID')) {
        $pieces = explode('.', PHP_VERSION);
        $version['number'] = intval(implode('', $pieces));
    } else {
        $version['number'] = intval(PHP_VERSION_ID);
    }
    $version['name'] = PHP_VERSION;
}

function settings($error = false) {
    $themes = array();
    $languages = array();
    $htaccess = is_writable(WEBROOT);

    if (($dh = opendir(APPROOT . '/themes'))) {
        while (($dirname = readdir($dh)) !== false) {
            if (strpos($dirname, '.') === false && is_dir(APPROOT . '/themes/' . $dirname)) {
                if (is_file(APPROOT . '/themes/' . $dirname . '/theme.xml')) {
                    $xml = new SimpleXMLIterator(APPROOT . '/themes/' . $dirname . '/theme.xml', LIBXML_NOCDATA, true);
                    if (strval($xml->type) === 'site') {
                        $themes[$dirname] = strval($xml->name);
                    }
                }
            }
        }
        closedir($dh);
    }

    $languages = findLanguages(DATAROOT . '/languages');

    $defaultHash = defaultHash();
    $defaultAdminPath = defaultAdminPath();
    $defaultShortDate = defaultShortDate();
    $defaultLongDate = defaultLongDate();
    $defaultTime = defaultTime();

    include './steps/settings.php';
}

function install() {
    $ufile = $sfile = $pcopy = true;
    //Create settings.xml
    $dom = new DOMDocument('1.0', 'UTF-8');
    $settings = $dom->createElement('settings');
    $settings->setAttribute('version', '1.0');

    if (!isset($_POST['sitename']) || !isset($_POST['sysemail'])) {
        settings('Site name and the system e-mail are required.');
        return;
    }

    if (!isset($_POST['name']) || !isset($_POST['password']) || $_POST['password'] == ''
            || !isset($_POST['password2']) || $_POST['password2'] == '') {

        settings('Your name and password are required.');
        return;
    }

    if ($_POST['password'] != $_POST['password2']) {
        settings('Your passwords don\'t match.');
        return;
    }

    $language = isset($_POST['language']) ? $_POST['language'] : 'en_US';
    $hideIndex = isset($_POST['hideindex']) ? 1 : 0;
    $adminPath = isset($_POST['adminpath']) ? $_POST['adminpath'] : defaultAdminPath();
    $shortDate = isset($_POST['shortdate']) ? $_POST['shortdate'] : defaultShortDate();
    $longDate = isset($_POST['longdate']) ? $_POST['longdate'] : defaultLongDate();
    $time = isset($_POST['time']) ? $_POST['time'] : defautTime();
    $hash = isset($_POST['hash']) ? $_POST['hash'] : defaultHash();

    $site = $dom->createElement('site');
    $site->appendChild($dom->createElement('home', 'welcome'));

    $name = $dom->createElement('name');
    $name->appendChild($dom->createCDATASection($_POST['sitename']));
    $site->appendChild($name);

    $site->appendChild($dom->createElement('theme', $_POST['theme']));
    $site->appendChild($dom->createElement('hideindex', $hideIndex));
    $settings->appendChild($site);

    $system = $dom->createElement('system');
    $system->appendChild($dom->createElement('email', $_POST['sysemail']));
    $system->appendChild($dom->createElement('path', $adminPath));
    $system->appendChild($dom->createElement('theme', defaultAdminTheme()));

    $locale = $dom->createElement('locale');
    $locale->appendChild($dom->createElement('language', $language));
    $locale->appendChild($dom->createElement('shortdateformat', $shortDate));
    $locale->appendChild($dom->createElement('longdateformat', $longDate));
    $locale->appendChild($dom->createElement('timeformat', $time));
    $system->appendChild($locale);

    $hashElem = $dom->createElement('hash');
    $hashElem->appendChild($dom->createCDATASection($hash));
    $system->appendChild($hashElem);

    $settings->appendChild($dom->createElement('updateinterval', '7'));
    $settings->appendChild($system);

    $dom->appendChild($settings);
    $sfile = $dom->save(DATAROOT . '/settings/settings.xml');

    //create users.xml
    $dom = new DOMDocument('1.0', 'UTF-8');
    $users = $dom->createElement('users');
    $users->setAttribute('version', '1.0');

    //name, email, password, password2
    $user = $dom->createElement('user');
    $name = $dom->createElement('name');
    $name->appendChild($dom->createCDATASection($_POST['name']));
    $user->appendChild($name);

    $user->appendChild($dom->createElement('password', hashPassword($_POST['password'], $hash)));
    $user->appendChild($dom->createElement('email', $_POST['email']));
    $user->appendChild($dom->createElement('active', 1));

    $users->appendChild($user);
    $dom->appendChild($users);
    $ufile = $dom->save(DATAROOT . '/settings/users.xml');

    //copy default pages
    $pcopy = copy('./base/404.xml', DATAROOT . '/pages/404.xml');
    $pcopy = copy('./base/welcome.xml', DATAROOT . '/pages/welcome.xml');
    $pcopy = copy('./base/about.xml', DATAROOT . '/pages/about.xml');
    $pcopy = copy('./base/contact.xml', DATAROOT . '/pages/contact.xml');

    //create .htaccess file
    if (isset($_POST['hideindex']) && is_writable(WEBROOT)) {
        copy('./base/temp.htaccess', WEBROOT . '/.htaccess');
    }
    include 'steps/final.php';
}

function defaultTime() {
    return 'g:i A';
}

function defaultShortDate() {
    return 'Y-m-d';
}

function defaultLongDate() {
    return 'D, d M Y';
}

function defaultAdminPath() {
    return 'admin';
}

function defaultHash() {
    $SimpleAsKidCudi = array('Simple', 'as', 'that', 'for', 'your', 'simple',
        'ass', 'Simple', 'way', 'I', 'wish', 'you', 'would', 'of', 'called', 'it',
        'how', 'it', 'should\'ve', 'been', 'They', 'try', 'to', 'tell', 'me', 'they',
        'don\'t', 'get', 'it', ',', 'they', 'don\'t', 'know', 'the', 'deal', 'Now',
        'I\'ll', 'be', 'damned', 'I', 'came', 'this', 'far', 'to', 'let', 'a', 'fool', 'live'
    );

    $max = count($SimpleAsKidCudi) - 1;
    $pieces = array();
    for ($i = 0; $i < 25; $i++) {
        ;
        $pieces[] = $SimpleAsKidCudi[rand(0, $max)];
    }
    return implode(' ', $pieces);
}

function defaultAdminTheme() {
    return 'SimpleDev';
}

//Must always be the same as the one in User model class.
function hashPassword($pass, $hash) {
    return sha1($pass . $hash);
}

function findLanguages($where) {
    $languages = array();

    if (($dh = opendir($where))) {
        while (($filename = readdir($dh)) !== false) {
            if (($pos = strpos($filename, '.php')) && $pos == (strlen($filename) - 4)) {
                $file = $where . '/' . $filename;
                $contents = file_get_contents($file);

                $found = array();
                if (preg_match_all('#/\*\*(.*?)\*/#sm', $contents, $found)) {
                    if (count($found) == 2) {
                        $pieces = explode('*', $found[1][0]);

                        foreach ($pieces as $piece) {
                            $piece = trim($piece);
                            //* @author * @version * @name     
                            if (strpos($piece, '@name') === 0) {
                                $info = explode('@name', $piece);
                                $info = trim(end($info));

                                $lang = explode('.', $filename);
                                $lang = $lang[0];

                                $languages[] = array($lang, $info);
                            }
                        }
                    }
                }
            }
        }
        closedir($dh);
    }

    return $languages;
}